package com.hamilton.erik.pt.mobile.android;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.mobile.android.app.MultiTaskProgressDialog;
import com.hamilton.erik.pt.mobile.android.volley.response.error.listener.DisplayErrorErrorListener;
import com.hamilton.erik.pt.mobile.client.VolleyJsonRestClient;
import com.hamilton.erik.pt.mobile.util.ResultUtil;
import com.hamilton.erik.pt.mobile.util.ServerUtil;

public class ViewAnimalActivity extends ViewDataActivity {

	private Animal animal = null;
	private ProgressDialog progressDialog = null;
	
	private final int EDIT_ACTIVITY = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_animal);
		
		findViewById(R.id.animal_view_edit_animal_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						edit();
					}
				});
		
		findViewById(R.id.animal_view_view_enclosure_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						viewEnclosure();
					}
				});
		
		findViewById(R.id.animal_view_view_feedings_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						viewFeedings();
					}
				});
		
		findViewById(R.id.animal_view_view_medical_records_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						viewMedicalRecords();
					}
				});
		
		findViewById(R.id.animal_view_view_notes_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						viewNotes();
					}
				});
		
		if (progressDialog == null) {
	        progressDialog = new MultiTaskProgressDialog(this,
	        								getString(R.string.progress_loading_title));
	    }
		
		retrieve(getIntent());		
		populateFields();
	}
	
	protected void retrieve(Intent intent) {
		animal = (Animal)intent
				.getSerializableExtra(
					getString(R.string.extra_animal_object));
		
		if(!TextUtils.isEmpty(animal.getName())) {
			setTitle(animal.getName());
		}
	}
		
	protected void populateFields() {
		if(animal != null) {
			String temp;

			temp = animal.getName();
			if(!TextUtils.isEmpty(temp)) {
				TextView nameTextView =
					(TextView)findViewById(R.id.animal_view_name_field);
				nameTextView.setText(temp);
			}

			temp = animal.getScientificName();
			if(!TextUtils.isEmpty(temp)) {				
				TextView scientificNameTextView =
					(TextView)findViewById(R.id.animal_view_scientific_name_field);
				scientificNameTextView.setText(temp);
			}

			temp = animal.getType();
			if(!TextUtils.isEmpty(temp)) {
				TextView typeTextView =
					(TextView)findViewById(R.id.animal_view_type_field);
				typeTextView.setText(temp);
			}

			if(animal.getGender() != null) {
				TextView genderTextView =
					(TextView)findViewById(R.id.animal_view_gender_field);
				genderTextView.setText(animal.getGender().toString());
			}

			temp = animal.getBirthDate();
			if(!TextUtils.isEmpty(temp)) {
				TextView birthDateTextView =
					(TextView)findViewById(R.id.animal_view_birth_date_field);
				birthDateTextView.setText(temp);
			}

			temp = animal.getPurchaseDate();
			if(!TextUtils.isEmpty(temp)) {
				TextView purchaseDateTextView =
					(TextView)findViewById(R.id.animal_view_purchase_date_field);
				purchaseDateTextView.setText(temp);
			}
		}
	}
		
	protected void edit() {
		Intent editAnimalActivity = new Intent(getApplicationContext(), EditAnimalActivity.class);
		editAnimalActivity.putExtra(getString(R.string.extra_animal_object), animal);
		startActivityForResult(editAnimalActivity, EDIT_ACTIVITY);
	}
	
	protected void delete() {
		StringBuilder url = new StringBuilder(ServerUtil.getInstance().buildAnimalPath());
		url.append("/delete/").append(animal.getId());
		
		if (progressDialog == null) {
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setTitle(getString(R.string.progress_deleting_title));
	        progressDialog.setMessage(getString(R.string.view_animal_progress_deleting_animal));
	    }
	    progressDialog.show();
		
		VolleyJsonRestClient.getClient().deleteJsonObject(url.toString(),
								new DeleteAnimalSuccessListener(),
								new DisplayErrorErrorListener(this, progressDialog));
	}
	
	private void viewEnclosure() {
		Intent viewEnclosureActivity = new Intent(getApplicationContext(), ViewEnclosureActivity.class);
		viewEnclosureActivity.putExtra(getString(R.string.extra_animal_object), animal);
		startActivity(viewEnclosureActivity);
	}
	
	private void viewFeedings() {
		Intent viewFeedingsActivity = new Intent(getApplicationContext(), FeedingListActivity.class);
		viewFeedingsActivity.putExtra(getString(R.string.extra_animal_object), animal);
		startActivity(viewFeedingsActivity);
	}
	
	private void viewMedicalRecords() {
		Intent viewMedicalRecordsActivity = new Intent(getApplicationContext(), MedicalRecordListActivity.class);
		viewMedicalRecordsActivity.putExtra(getString(R.string.extra_animal_object), animal);
		startActivity(viewMedicalRecordsActivity);
	}
	
	private void viewNotes() {
		Intent noteListActivity = new Intent(getApplicationContext(), NoteListActivity.class);
		noteListActivity.putExtra(getString(R.string.extra_animal_object), animal);
		noteListActivity.putExtra(getString(R.string.extra_note_reference_id), animal.getId());
		noteListActivity.putExtra(getString(R.string.extra_note_base_rest_path), ServerUtil.getInstance().buildAnimalPath());
		startActivity(noteListActivity);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_animal, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch(item.getItemId()) {
			case R.id.action_view_animal_edit :
				edit();
				return true;
			case R.id.action_view_animal_delete :
				delete();
			default :
				return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == EDIT_ACTIVITY && resultCode == ResultUtil.RESULT_SUCCESS) {
			isEdited = true;
			retrieve(data);
			populateFields();
		}
	}
	
	// Catch the back button(After 2.0)
	@Override
	public void onBackPressed() {
		finishWithResult();
	}

	// Catch the back button(Before 2.0)
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishWithResult();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public void finishWithResult() {
		if(isEdited) {
			setResult(ResultUtil.EDITED);
		}

		finish();		
	}
	
	private class DeleteAnimalSuccessListener implements Response.Listener<JSONObject> {

		@Override
		public void onResponse(JSONObject response) {
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			
			setResult(ResultUtil.DELETED, null);
			finish();
		}
	}

}
